/*
 * Copyright (c) 2009 Keith Lazuka
 * License: http://www.opensource.org/licenses/mit-license.html
 */

#import <sqlite3.h>

#import "TodaysPlanSqliteDataSource.h"
#import "TodaysPlan.h"
#import "SqliteDB.h"

static BOOL IsDateBetweenInclusive(NSDate *date, NSDate *begin, NSDate *end)
{
  return [date compare:begin] != NSOrderedAscending && [date compare:end] != NSOrderedDescending;
}

@interface TodaysPlanSqliteDataSource ()
- (NSArray *)holidaysFrom:(NSDate *)fromDate to:(NSDate *)toDate;
@end

@implementation TodaysPlanSqliteDataSource
@synthesize items,holidays;

+ (TodaysPlanSqliteDataSource *)dataSource
{
  return [[[[self class] alloc] init] autorelease];
}

- (id)init
{
  if ((self = [super init])) {
    items = [[NSMutableArray alloc] init];
    holidays = [[NSMutableArray alloc] init];
  }

  return self;
}

- (TodaysPlan *)holidayAtIndexPath:(NSIndexPath *)indexPath
{
  return [items objectAtIndex:indexPath.row];
}

#pragma mark UITableViewDataSource protocol conformance

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *identifier = @"MyCell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    if (!cell) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier] autorelease];
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
        cell.selectionStyle = UITableViewCellSelectionStyleBlue;
        cell.imageView.contentMode = UIViewContentModeScaleAspectFill;
    }
  
    TodaysPlan *TodaysPlan = [self holidayAtIndexPath:indexPath];
    cell.textLabel.text = TodaysPlan.task;
    return cell;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
  return [items count];
}

#pragma mark Sqlite access

- (NSString *)databasePath
{
    SqliteDB *db = [[[SqliteDB alloc]init] autorelease];
    [db initializeDatabaseIfNeeded];
    NSString* dbPath = [SqliteDB getDatabaseFilePath];
  //return [[NSBundle mainBundle] pathForResource:@"holidays" ofType:@"db"];
    return dbPath;
}

- (void)loadHolidaysFrom:(NSDate *)fromDate to:(NSDate *)toDate delegate:(id<KalDataSourceCallbacks>)delegate
{
    DLog(@"Fetching holidays from the database between %@ and %@...", fromDate, toDate);
    sqlite3 *db;
    NSDateFormatter *fmt = [[[NSDateFormatter alloc] init] autorelease];
	if(sqlite3_open([[self databasePath] UTF8String], &db) == SQLITE_OK) {
        const char *sql = "select id, registdate, task, memo, priority, done, reminderdate, reminder from todays_plan";
        sqlite3_stmt *stmt;
        if(sqlite3_prepare_v2(db, sql, -1, &stmt, NULL) == SQLITE_OK) {
            [fmt setDateFormat:@"yyyy-MM-dd"];
			while(sqlite3_step(stmt) == SQLITE_ROW) {
                int pkey = sqlite3_column_int(stmt, 0);
                NSString *dateAsText =[NSString stringWithUTF8String:(char *)sqlite3_column_text(stmt, 1)];
                NSString *task =[NSString stringWithUTF8String:(char *)sqlite3_column_text(stmt, 2)];
                NSString *memo =[NSString stringWithUTF8String:(char *)sqlite3_column_text(stmt, 3)];
                NSString *priority =[NSString stringWithUTF8String:(char *)sqlite3_column_text(stmt, 4)];
                NSString *done = [NSString stringWithUTF8String:(char *)sqlite3_column_text(stmt, 5)];
                NSString *reminderDate = [NSString stringWithUTF8String:(char *)sqlite3_column_text(stmt,6)];
                BOOL reminder = sqlite3_column_int(stmt,7) ? YES : NO;
                [holidays addObject:[TodaysPlan holidayNamed:pkey date:[fmt dateFromString:dateAsText] task:task memo:memo priority:priority done:done reminderDate:reminderDate reminder:reminder]];
            }
		}
		sqlite3_finalize(stmt);
	}
	sqlite3_close(db);
  [delegate loadedDataSource:self];
}

#pragma mark KalDataSource protocol conformance

- (void)presentingDatesFrom:(NSDate *)fromDate to:(NSDate *)toDate delegate:(id<KalDataSourceCallbacks>)delegate
{
  [holidays removeAllObjects];
  [self loadHolidaysFrom:fromDate to:toDate delegate:delegate];
}

- (NSArray *)markedDatesFrom:(NSDate *)fromDate to:(NSDate *)toDate
{
  return [[self holidaysFrom:fromDate to:toDate] valueForKeyPath:@"date"];
}

- (void)loadItemsFromDate:(NSDate *)fromDate toDate:(NSDate *)toDate
{
  [items addObjectsFromArray:[self holidaysFrom:fromDate to:toDate]];
}

- (void)removeAllItems
{
  [items removeAllObjects];
}

#pragma mark -

- (NSArray *)holidaysFrom:(NSDate *)fromDate to:(NSDate *)toDate
{
  NSMutableArray *matches = [NSMutableArray array];
  for (TodaysPlan *TodaysPlan in holidays)
    if (IsDateBetweenInclusive(TodaysPlan.date, fromDate, toDate))
      [matches addObject:TodaysPlan];
  
  return matches;
}

- (void)dealloc
{
  [items release];
  [holidays release];
  [super dealloc];
}

@end
